<?php

namespace app\common\logic;

use app\common\library\MemberVo;
use app\common\model\Coupon;
use app\common\model\CouponSetting;
use think\db\Query;
use think\Log;

class CouponSettingLogic extends BaseLogic
{
    public $model;

    public function assignModel()
    {
        $this->model          = new CouponSetting();
    }
    public function handleSearch(Query $query, array $params): Query
    {
        $query->where('status',1);
        $query->where('coupon_nums','>',0);//还可领取数量
        $query->where('get_begin_time','<',time());//开始领取时间
        $query->where('get_end_time','>',time());//截止领取时间
        return $query;
    }

    /**
     * 待领取优惠券列表
     * @return mixed
     */
    public function index($params)
    {
        $params['field'] = "id,name,money,rule,least_cost,get_limit,coupon_nums,remark,get_begin_time begin_time,get_end_time end_time";
        $list = $this->getList($params)->toArray();
        Log::info($list);
        $new_list = [];
        foreach ($list as $k=>&$v){
            if ($v['rule'] == 2){
                if (!CouponSetting::checkCurrentAllowGetBrithdayCouponByMemberId(MemberVo::instance()->getMemberId())){
                    unset($list[$k]);
                    continue;
                }
            }
            if ($v['rule'] == 1){
                if (!CouponSetting::checkCurrentAllowGetCouponByMemberId(MemberVo::instance()->getMemberId())){
                    unset($list[$k]);
                    continue;
                }
            }
            $all_num = Coupon::where(['setting_id'=>$v['id']])->count('id');
            if ($v['coupon_nums'] <= $all_num){
                unset($list[$k]);
                continue;
            }
            $num = Coupon::where(['member_id'=>MemberVo::instance()->getMemberId(),'setting_id'=>$v['id']])->count('id');
            if ($v['get_limit'] <= $num){
                unset($list[$k]);
                continue;
            }
            unset($v['rule']);
//            $v['desc'] = $v['remark'];
            $v['desc'] = $v['least_cost'] == 0 ? "无门槛" : "满{$v['least_cost']}元可用";
            unset($v['remark']);
            $new_list[] = $v;

        }
        return $new_list;
    }




}